# Docker HTTPS 设置脚本
param(
    [switch]$GenerateCerts = $false,
    [switch]$Deploy = $false,
    [switch]$Clean = $false,
    [string]$Domain = "localhost"
)

function Write-Info($Message, $Color = "White") {
    Write-Host $Message -ForegroundColor $Color
}

function Generate-SelfSignedCert {
    Write-Info "🔐 生成自签名证书..." "Blue"
    
    # 创建证书目录
    if (!(Test-Path "certs")) {
        New-Item -ItemType Directory -Path "certs"
    }

    try {
        # 生成自签名证书
        $cert = New-SelfSignedCertificate `
            -DnsName $Domain, "webrtc-app", "*.localhost" `
            -CertStoreLocation "cert:\LocalMachine\My" `
            -KeyAlgorithm RSA `
            -KeyLength 2048 `
            -HashAlgorithm SHA256 `
            -NotAfter (Get-Date).AddYears(1) `
            -Subject "CN=$Domain" `
            -FriendlyName "WebRTC Development Certificate"

        # 导出证书和私钥
        $certPath = "certs\webrtc-dev.crt"
        $keyPath = "certs\webrtc-dev.key"
        $pfxPath = "certs\webrtc-dev.pfx"
        $password = "webrtc123"

        # 导出 PFX 格式（包含私钥）
        $securePassword = ConvertTo-SecureString -String $password -Force -AsPlainText
        Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $securePassword | Out-Null

        # 导出 CRT 格式（公钥）
        Export-Certificate -Cert $cert -FilePath $certPath | Out-Null

        # 使用 OpenSSL 导出私钥（如果可用）
        if (Get-Command openssl -ErrorAction SilentlyContinue) {
            openssl pkcs12 -in $pfxPath -nocerts -out $keyPath -nodes -passin "pass:$password"
            openssl pkcs12 -in $pfxPath -clcerts -nokeys -out $certPath -passin "pass:$password"
        }

        Write-Info "✅ 证书生成成功:" "Green"
        Write-Info "   - 证书文件: $certPath" "Cyan"
        Write-Info "   - 私钥文件: $keyPath" "Cyan"
        Write-Info "   - PFX 文件: $pfxPath" "Cyan"
        Write-Info "   - 密码: $password" "Yellow"

        # 清理证书存储
        Remove-Item -Path "cert:\LocalMachine\My\$($cert.Thumbprint)" -Force

        return @{
            CertPath = $certPath
            KeyPath = $keyPath
            PfxPath = $pfxPath
            Password = $password
        }
    }
    catch {
        Write-Info "❌ 证书生成失败: $($_.Exception.Message)" "Red"
        throw
    }
}

function Update-DockerComposeForHttps {
    param($CertInfo)
    
    Write-Info "🔧 更新 Docker Compose 配置..." "Blue"
    
    # 备份原配置
    if (Test-Path "docker-compose.yml") {
        Copy-Item "docker-compose.yml" "docker-compose.yml.backup"
    }

    # 读取配置内容
    $content = Get-Content "docker-compose.yml" -Raw
    
    # 更新环境变量
    $content = $content -replace 'ASPNETCORE_URLS=http://\+:5000', 'ASPNETCORE_URLS=https://+:5001;http://+:5000'
    $content = $content -replace '# - "5001:5001"', '- "5001:5001"'
    $content = $content -replace 'ServicePort=5000', 'ServicePort=5001'
    
    # 添加证书配置
    $httpsConfig = @"
      - ASPNETCORE_HTTPS_PORT=5001
      - ASPNETCORE_Kestrel__Certificates__Default__Path=/app/certs/webrtc-dev.pfx
      - ASPNETCORE_Kestrel__Certificates__Default__Password=$($CertInfo.Password)
"@
    
    $content = $content -replace '(# 注释掉 HTTPS 相关配置\r?\n)(.*?)(# RabbitMQ)', "`$1$httpsConfig`r`n      `$3"
    
    # 保存更新的配置
    Set-Content "docker-compose.yml" -Value $content -Encoding UTF8
    
    Write-Info "✅ Docker Compose 配置已更新" "Green"
}

function Deploy-Application {
    Write-Info "🚀 部署应用..." "Blue"
    
    try {
        # 停止现有容器
        docker-compose down 2>$null
        
        # 构建并启动
        docker-compose up -d --build
        
        if ($LASTEXITCODE -eq 0) {
            Write-Info "✅ 应用部署成功!" "Green"
            Write-Info "📱 访问地址:" "Cyan"
            Write-Info "   - HTTPS: https://localhost:5001" "Green"
            Write-Info "   - HTTP:  http://localhost:5000" "Yellow"
            Write-Info "" 
            Write-Info "⚠️  注意: 首次访问需要在浏览器中接受自签名证书" "Yellow"
        } else {
            Write-Info "❌ 部署失败" "Red"
            docker-compose logs --tail=50
        }
    }
    catch {
        Write-Info "❌ 部署过程中发生错误: $($_.Exception.Message)" "Red"
        throw
    }
}

function Clean-Environment {
    Write-Info "🧹 清理环境..." "Blue"
    
    # 停止容器
    docker-compose down 2>$null
    
    # 删除生成的证书
    if (Test-Path "certs") {
        Remove-Item -Recurse -Force "certs"
    }
    
    # 恢复配置文件
    if (Test-Path "docker-compose.yml.backup") {
        Move-Item "docker-compose.yml.backup" "docker-compose.yml" -Force
    }
    
    Write-Info "✅ 环境清理完成" "Green"
}

# 主执行逻辑
Write-Info "================================================" "Cyan"
Write-Info "   WebRTC Docker HTTPS 配置工具" "Cyan"
Write-Info "================================================" "Cyan"

try {
    if ($Clean) {
        Clean-Environment
        exit 0
    }

    if ($GenerateCerts) {
        $certInfo = Generate-SelfSignedCert
        Update-DockerComposeForHttps -CertInfo $certInfo
        
        if ($Deploy) {
            Deploy-Application
        } else {
            Write-Info "💡 运行以下命令来部署应用:" "Yellow"
            Write-Info "   .\scripts\setup-docker-https.ps1 -Deploy" "Cyan"
        }
    } elseif ($Deploy) {
        Deploy-Application
    } else {
        Write-Info "使用方法:" "Yellow"
        Write-Info "  .\scripts\setup-docker-https.ps1 -GenerateCerts        # 生成证书并配置" "Cyan"
        Write-Info "  .\scripts\setup-docker-https.ps1 -GenerateCerts -Deploy # 生成证书、配置并部署" "Cyan"
        Write-Info "  .\scripts\setup-docker-https.ps1 -Deploy               # 部署应用" "Cyan"
        Write-Info "  .\scripts\setup-docker-https.ps1 -Clean                # 清理环境" "Cyan"
    }
}
catch {
    Write-Info "❌ 执行失败: $($_.Exception.Message)" "Red"
    exit 1
} 